package icedot.library.common.base;

import android.os.AsyncTask;

import java.util.Calendar;

import icedot.library.common.utils.StringUtils;

/**
 * Created by IceDot on 2015/11/9.
 */
public class TaskTimeOut extends AsyncTask<Void,Void,Void>
{
    private static final int s_running = 1;     //运行中
    private static final int s_stop = 0;     //停止
    private static final int s_timeout = 2;     //超时

    private int _status = s_running;        //当前状态
    private int _timeOut = 30000;           //默认的超时时间
    private long _startTime = 0;            //开始时间
    private BaseDlgFragment _dlg = null;
    private BaseActivity _act = null;
    private String _content = "你的操作已超时!";

    public void setActivity(BaseActivity act)
    {
        _act = act;
    }
    public void setDlg(BaseDlgFragment dlg)
    {
        _dlg = dlg;
    }
    public void setTimeOutSecond(int second)
    {
        _timeOut = second * 1000;
    }

    public void cancelRunning()
    {
        _status = s_stop;
    }

    public void setTimeOutMsg(String msg)
    {
        _content = msg;
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        try
        {
            _startTime = Calendar.getInstance().getTimeInMillis();
            while(_status == s_running)
            {
                Thread.sleep(200);
                if(Calendar.getInstance().getTimeInMillis() - _startTime > _timeOut)
                {
                    _status = s_timeout;
                    break;
                }
            }
        }
        catch (InterruptedException e)
        {
            _status = s_stop;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);
        if(_status == s_timeout)
        {
            if(_dlg != null)
            {
                _dlg.dismiss();
            }
            if(_act != null && !StringUtils.isNullOrEmpty(_content))
            {
                Logger.showHintMsg(_act,_content);
            }
        }
    }
}

